﻿using System;
using SDCloudSolution.SDCloud.Web.Infrastructure.Interfaces;

namespace SDCloudSolution.SDCloud.Web.Infrastructure
{
    public class DataSizeFormatter : IDataSizeFormatter
    {
        /// <summary>
        /// Converts the bytes count to user friendly format.
        /// F.e. converts 11000 bytes to "11 KB" string.
        /// </summary>
        /// <param name="sizeInBytes">The size in bytes.</param>
        /// <returns>The user friendly string representation of this size.</returns>
        public string ConvertBytesToUserFriendlyFormat(long sizeInBytes)
        {
            if (sizeInBytes < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(sizeInBytes), "Size should be is positive or zero.");
            }

            var sizeNames = new[]
            {
                "B", "KB", "MB", "GB", "TB"
            };

            double displayedValue = sizeInBytes;
            var displayedNameIndex = 0;
            while (displayedValue > 800 && displayedNameIndex < sizeNames.Length - 1)
            {
                displayedValue /= 1024.0;
                displayedNameIndex++;
            }

            return $"{displayedValue:00.00} {sizeNames[displayedNameIndex]}";
        }
    }
}